package com.example.cqcet_demo.fragment;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;

import com.example.cqcet_demo.R;
import com.example.cqcet_demo.adapter.MyListViewUserInfoAdapter;
import com.example.cqcet_demo.uitls.OkHttpUtil;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class UserInfoFragment extends Fragment {

    private ImageView iv_headImg;
    private OkHttpClient okHttpClient;
    private Handler mhandler;
    private String url ="http://ecard.cqcet.edu.cn/Cardholder/";
    private final String USERINFOURL = "http://ecard.cqcet.edu.cn/Cardholder/AccInfo.aspx";
    private View view;
    private ListView lv_userInfo;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(view==null) {
            view = inflater.inflate(R.layout.activity_userinfo, container, false);
            getData();
        }
        return view;

    }

    private void getHeadImg() {
        new Thread(){
            @Override
            public void run() {
                okHttpClient = OkHttpUtil.getInstance();
                Request res = new Request.Builder().url(USERINFOURL).get().build();
                try {
                    Response rsp = okHttpClient.newCall(res).execute();
                    if(rsp.isSuccessful()){

                        String data = rsp.body().string();
                        Document doc = Jsoup.parse(data, "GBK");
                        Elements trs = doc.getElementById("Panel0").select("tr");
                        List userInfos = new ArrayList();
                        for (int i = 0;i < trs.size();i++){
                            Elements tds = trs.get(i).select("td");
                            for (int j = 0;j < tds.size()-1;j+=2){
                                String td1 = tds.get(j).text().replace(" ","");
                                String td2 = tds.get(j+1).text().replace(" ","");
                                if(td1.isEmpty() || td2.isEmpty())
                                    break;
                                userInfos.add(td1+":"+td2);
                            }
                        }
                        String accountNumber = doc.getElementById("Image1").attr("src");
                        url += accountNumber;
                        res = new Request.Builder().url(url).get().build();
                        okHttpClient.newCall(res).enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                            }

                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                Message msg = new Message();
                                byte[] bytes = response.body().bytes();
                                Bitmap btm = BitmapFactory.decodeByteArray(bytes,0,bytes.length);
                                Log.d("succed","访问成功");
                                msg.what = 0x1221;
                                msg.obj = btm;

                                mhandler.sendMessage(msg);
                            }
                        });
                        Message msg = new Message();
                        msg.what=0x1222;
                        msg.obj=userInfos;
                        mhandler.sendMessage(msg);
                    }
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private void initView() {
        iv_headImg = (ImageView) view.findViewById(R.id.iv_headImg);
        lv_userInfo = (ListView)view.findViewById(R.id.lv_userInfo);

    }

    protected void getData() {
        initView();
        Log.d("userinfo","已经执行");
        mhandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 0x1221:
                        Bitmap bitmap = (Bitmap) msg.obj;
                        if(bitmap==null)
                            break;
                        if(bitmap.getHeight()>200)
                            iv_headImg.setImageBitmap(createCircleImage(bitmap, 300));
                        break;
                    case 0x1222:

                        lv_userInfo.setAdapter(new MyListViewUserInfoAdapter(getContext(), (List) msg.obj));
                        break;
                }
            }
        };
        getHeadImg();
    }

    private Bitmap createCircleImage(Bitmap source, int min)
    {
        source = source.copy(Bitmap.Config.ARGB_8888, true);
        final Paint paint = new Paint();
        paint.setAntiAlias(true);
        Bitmap target = Bitmap.createBitmap(min, min, Bitmap.Config.ARGB_8888);
        /**
         * 产生一个同样大小的画布
         */
        Canvas canvas = new Canvas(target);
        /**
         * 首先绘制圆形
         */
        canvas.drawCircle(min / 2, min / 2, min / 2, paint);

        /**
         * 使用SRC_IN
         */
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        paint.setColor(Color.GREEN);
        /**
         * 绘制图片
         */
        if(source.getHeight()>200)
            canvas.drawBitmap(source, 25,0, paint);

        return target;
    }
}
